package com.sgb.kjwl.view.ui.activity.self.shop;

import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;

import com.apeng.permissions.EsayPermissions;
import com.apeng.permissions.OnPermission;
import com.bumptech.glide.Glide;
import com.mob.MobSDK;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityShareBinding;
import com.sgb.kjwl.model.entity.ShareSDKUtilsEntity;
import com.swgk.core.util.MToast;
import com.swgk.core.util.qrcode.QRCodeUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.List;

import cn.sharesdk.dingding.friends.Dingding;
import cn.sharesdk.dingding.utils.DingdingClientNotExistException;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.tencent.qq.QQClientNotExistException;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;
import cn.sharesdk.wechat.utils.WechatClientNotExistException;

/**
 * @author PC
 */
public class ShareActivity extends Activity {

    ActivityShareBinding binding;
    String picName;
    String mainPic;
    String title;
    String price;
    String shopPath;
    String phone;

    public static void start(Context context, String picName, String mainPic, String title, String price, String shopPath, String phone) {
        Intent intent = new Intent();
        intent.putExtra("picName", picName);
        intent.putExtra("mainPic", mainPic);
        intent.putExtra("title", title);
        intent.putExtra("price", price);
        intent.putExtra("shopPath", shopPath);
        intent.putExtra("phone", phone);
        intent.setClass(context, ShareActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_share);
        picName = getIntent().getStringExtra("picName");
        mainPic = getIntent().getStringExtra("mainPic");
        title = getIntent().getStringExtra("title");
        price = getIntent().getStringExtra("price");
        shopPath = getIntent().getStringExtra("shopPath");
        phone = getIntent().getStringExtra("phone");
        initView();

    }

    private void initView() {
        Glide.with(this).load(mainPic).into(binding.ivCommodity);
        binding.ivQrCode.setImageBitmap(QRCodeUtils.createQRCode(shopPath));
        binding.tvCommodityName.setText(title);
        binding.tvCommodityPrice.setText(price);
        binding.tvDingding.setOnClickListener(v -> {
            ShareSDKUtilsEntity bean = new ShareSDKUtilsEntity();
            bean.setTitle(title);
            bean.setText("咨询热线：" + phone);
            bean.setImageUrl(mainPic);
            bean.setUrl(shopPath);
            bean.setShareType(Dingding.NAME);
            bean.setToastText("钉钉");
            bean.setToastShow(true);
            shareShow(ShareActivity.this, bean);
        });
        binding.tvWechat.setOnClickListener(v -> {
            ShareSDKUtilsEntity bean = new ShareSDKUtilsEntity();
            bean.setTitle(title);
            bean.setText("咨询热线：" + phone);
            bean.setImageUrl(mainPic);
            bean.setUrl(shopPath);
            bean.setShareType(Wechat.NAME);
            bean.setToastText("微信");
            bean.setToastShow(true);
            shareShow(ShareActivity.this, bean);
        });
        binding.tvWechatMoments.setOnClickListener(v -> {
            ShareSDKUtilsEntity bean = new ShareSDKUtilsEntity();
            bean.setTitle(title);
            bean.setText("咨询热线：" + phone);
            bean.setImageUrl(mainPic);
            bean.setUrl(shopPath);
            bean.setShareType(WechatMoments.NAME);
            bean.setToastText("朋友圈");
            bean.setToastShow(true);
            shareShow(ShareActivity.this, bean);
        });
        binding.tvQq.setOnClickListener(v -> {
            ShareSDKUtilsEntity bean = new ShareSDKUtilsEntity();
            bean.setTitle(title);
            bean.setText("咨询热线：" + phone);
            bean.setImageUrl(mainPic);
            bean.setUrl(shopPath);
            bean.setShareType(QQ.NAME);
            bean.setToastText("QQ");
            bean.setToastShow(true);
            shareShow(ShareActivity.this, bean);
        });
        binding.tvCopy.setOnClickListener(v -> {
            //获取剪贴板管理器：
            ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
            // 创建普通字符型ClipData
            ClipData mClipData = ClipData.newPlainText("Label", shopPath);
            // 将ClipData内容放到系统剪贴板里。
            cm.setPrimaryClip(mClipData);
            MToast.showToast(ShareActivity.this, "复制成功！");
            finish();
        });
        binding.tvSave.setOnClickListener(v -> {
            boolean hasPermission = EsayPermissions.isHasPermission(ShareActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
            if (hasPermission) {
                saveBitmapFromView(binding.picLayout);
            } else {
                EsayPermissions.with(ShareActivity.this).permission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE).request(new OnPermission() {
                    @Override
                    public void hasPermission(List<String> granted, boolean isAll) {
                        saveBitmapFromView(binding.picLayout);
                    }

                    @Override
                    public void noPermission(List<String> denied, boolean quick) {
                        MToast.showToast(ShareActivity.this, "存储权限未开启");
                    }
                });
            }

        });
        binding.tvCancel.setOnClickListener(v -> {
            finish();
        });
    }


    public void shareShow(Context context, ShareSDKUtilsEntity shareBean) {
        MobSDK.submitPolicyGrantResult(true, null);
        Platform.ShareParams sp = new Platform.ShareParams();
        sp.setTitle(shareBean.getTitle());
        sp.setText(shareBean.getText());
        sp.setImageUrl(shareBean.getImageUrl());
        //qq平台需要
        sp.setTitleUrl(shareBean.getUrl());
        sp.setUrl(shareBean.getUrl());
        sp.setShareType(Platform.SHARE_WEBPAGE);
        Platform qzone = ShareSDK.getPlatform(shareBean.getShareType());
        if (qzone == null) {
            MToast.showToast(ShareActivity.this, "分享服务升级中，暂不可用~");
            return;
        }
        // 设置分享事件回调（注：回调放在不能保证在主线程调用，不可以在里面直接处理UI操作）
        qzone.setPlatformActionListener(new PlatformActionListener() {
            @Override
            public void onError(Platform arg0, int arg1, Throwable arg2) {
                //失败的回调，arg:平台对象，arg1:表示当前的动作，arg2:异常信息
                if (arg2 instanceof DingdingClientNotExistException) {
                    MToast.showToast(context, "您未安装钉钉客户端，分享失败！");
                }
                if (arg2 instanceof WechatClientNotExistException) {
                    MToast.showToast(context, "您未安装微信客户端，分享失败！");
                }
                if (arg2 instanceof QQClientNotExistException) {
                    MToast.showToast(context, "您未安装QQ客户端，分享失败！");
                }
            }

            @Override
            public void onComplete(Platform arg0, int arg1, HashMap arg2) {
                Log.e("tag", "分享成功................");
                //分享成功的回调
                MToast.showToast(context, "分享成功！");
                ShareActivity.this.finish();
            }

            @Override
            public void onCancel(Platform arg0, int arg1) {
                MToast.showToast(context, "分享取消！");
                ShareActivity.this.finish();
            }
        });
        // 执行图文分享
        qzone.share(sp);
    }

    public void saveBitmapFromView(View view) {
        int w = view.getWidth();
        int h = view.getHeight();
        Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(bmp);
        c.drawColor(Color.WHITE);
//        view.layout(AbScreenUtils.dp2px(ShareActivity.this, 80), AbScreenUtils.dp2px(ShareActivity.this, 106), w, h);
        view.draw(c);
//        ImageUtils.save2Album(bmp, Bitmap.CompressFormat.JPEG);
//        MToast.showToast(ShareActivity.this, "保存成功！");
        saveImageToGallery(bmp, picName + ".jpeg");
    }


//    public static String saveBitmap2(Bitmap paramBitmap, String paramString) {
//        try {
//            File file = new File(paramString);
//            if (!file.exists()) {
//                file.getParentFile().mkdirs();
//                file.createNewFile();
//            }
//            FileOutputStream fileOutputStream = new FileOutputStream(file);
//            paramBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
//            fileOutputStream.flush();
//            fileOutputStream.close();
//            return file.getAbsolutePath();
//        } catch (IOException e) {
//            e.printStackTrace();
//            return null;
//        }
//    }

    /* 保存文件，文件名为当前日期*/
//    public void saveBitmap(Bitmap bitmap, String bitName) {
////        ImageUtils.save2Album(bitmap, Bitmap.CompressFormat.JPEG);
//
//        String fileName;
//        if ("Xiaomi".equals(Build.BRAND)) {// 小米手机   Pictures
//            fileName =
//                    Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/" + bitName;
//        } else {// Meizu 、Oppo
//            fileName = Environment.getExternalStorageDirectory().getPath() + "/DCIM/" + bitName;
//        }
//        File file = new File(fileName);
//        if (file.exists()) {
//            file.delete();
//        }
//        FileOutputStream out;
//        try {
//            out = new FileOutputStream(file);
//            // 格式为 JPEG，照相机拍出的图片为JPEG格式的，PNG格式的不能显示在相册中
//            if (bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out)) {
//                out.flush();
//                out.close();
//                // 插入图库
//                MediaStore.Images.Media.insertImage(
//                        this.getContentResolver(),
//                        file.getAbsolutePath(),
//                        bitName,
//                        null
//                );
//                MToast.showToast(ShareActivity.this, "保存成功！");
//            }
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }

    public void saveImageToGallery(Bitmap bitmap, String bitName) {
        String storePath =
                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath() + "/SGB/";
        File appDir = new File(storePath);
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        File file = new File(storePath, bitName);
        if (file.exists()) {
            file.delete();
        }
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(file);
            if (bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out)) {
                out.flush();
                out.close();
                // 插入图库
                MediaStore.Images.Media.insertImage(
                        this.getContentResolver(),
                        file.getAbsolutePath(),
                        bitName,
                        null
                );
                MToast.showToast(ShareActivity.this, "保存图片成功！");
                finish();
            } else {
                MToast.showToast(ShareActivity.this, "保存图片失败！");
            }
        } catch (Exception e) {
            MToast.showToast(ShareActivity.this, "保存图片失败！");
            e.printStackTrace();
        }
    }
}
